﻿using ApiGateway;
using ApiGateway.Interface;
using ApiGateway.Model;
using HttpApiGateway.Config;
using HttpApiGateway.Interface;
using System;

namespace HttpApiGateway
{
    internal class ApiGatewayService
    {
        private static IApiDocModular _ApiDoc => RpcClient.RpcClient.Unity.Resolve<IApiDocModular>();
        private static readonly IHttpConfig _Config = new Config.HttpConfig();
        public static IHttpConfig Config => _Config;

        static ApiGatewayService()
        {
            RpcClient.RpcClient.Unity.RegisterInstance<IHttpConfig>(_Config);
            GatewayServer.Starting += GatewayServer_Starting;
            GatewayServer.Closeing += GatewayServer_Closeing;
        }

        private static void GatewayServer_Closeing()
        {
            HttpService.HttpService.StopService();
        }

        private static void GatewayServer_Starting()
        {
            RpcClient.RpcClient.Unity.Load("ApiGateway");
            ApiPlugInService.Init();
            GatewayServer.RegModular(new GatewayModular());
            HttpService.HttpService.RegService(Config.Url);
        }

        internal static string GetApiShow(Uri uri)
        {
            if (_ApiDoc == null)
            {
                return string.Empty;
            }
            return _ApiDoc.GetApiShow(uri);
        }

        internal static void RegModular(string name, Type source)
        {
            if (_ApiDoc != null)
            {
                _ApiDoc.RegModular(name, source, _Config.Url);
            }
        }
        internal static void RegApi(ApiFuncBody api)
        {
            if (_ApiDoc != null)
            {
                _ApiDoc.RegApi(api);
            }
        }
    }
}
